import userService from "../service/user.service.js";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import { JWT_SECRET } from "../constant/default.js";

const verifyUserIsExist = async (ctx, next) => {
  const { user_name } = ctx.request.body;

  const isAlive = await userService.getUerInfo({ user_name });

  if (isAlive) {
    ctx.status = 409;
    ctx.body = {
      code: 10002,
      message: "user is already alive",
      result: {},
    };
    return;
  }

  await next();
};

const verifyUserLogin = async (ctx, next) => {
  const { user_name, password } = ctx.request.body;

  const isAlive = await userService.getUerInfo({ user_name });

  if (!isAlive) {
    ctx.status = 409;
    ctx.body = {
      code: 10003,
      message: "userName is not exist",
      result: {},
    };
    return;
  }

  if (!bcrypt.compareSync(password, isAlive.dataValues.password)) {
    ctx.status = 400;
    ctx.body = {
      code: 10004,
      message: "userName or password is error",
      result: {},
    };
    return;
  }

  await next();
};

const verifyUserIsNull = async (ctx, next) => {
  let { user_name, password } = ctx.request.body;

  if (!user_name || !password) {
    ctx.status = 400;
    ctx.body = {
      code: 10001,
      message: "userName or password is null",
      result: {},
    };
    return;
  }

  await next();
};

const verifyUserToken = async (ctx, next) => {
  let { authorization } = ctx.request.header;

  if (!authorization) {
    ctx.status = 400;
    ctx.body = {
      code: 10006,
      message: "Token is not exist",
      result: {},
    };
    return;
  }

  authorization = authorization.replace("Bearer ", "");
  try {
    const user = jwt.verify(authorization, JWT_SECRET);
    ctx.state.user = user;
  } catch (error) {
    console.log(error.name + "zkhhh");
    switch (error.name) {
      case "TokenExpiredError":
        ctx.status = 400;
        ctx.body = {
          code: 10006,
          message: "TokenExpiredError",
          result: {},
        };
        return;
      case "JsonWebTokenError":
        ctx.status = 400;
        ctx.body = {
          code: 10006,
          message: "JsonWebTokenError",
          result: {},
        };
        return;
    }
  }

  await next();
};

const bcryptPassWord = async (ctx, next) => {
  const { password } = ctx.request.body;
  const salt = bcrypt.genSaltSync(2);
  const hash = bcrypt.hashSync(password, salt);

  ctx.request.body.password = hash;

  await next();
};

export {
  verifyUserIsExist,
  verifyUserIsNull,
  verifyUserLogin,
  bcryptPassWord,
  verifyUserToken,
};
